package com.spike.servlet;

import com.spike.model.Dept;
import com.spike.model.Emp;
import com.spike.service.DeptService;
import com.spike.service.EmpService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/empUpdate")
public class EmpUpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        DeptService deptService = new DeptService();
        EmpService empService = new EmpService();
        Emp emp = new Emp();
        emp.setId(Integer.parseInt(req.getParameter("id")));
        emp.setName(req.getParameter("name"));
        emp.setSex(req.getParameter("sex").charAt(0));
        emp.setSalary(Double.parseDouble(req.getParameter("salary")));
        emp.setAge(Integer.parseInt(req.getParameter("age")));
        emp.setStatus(req.getParameter("status"));
        req.getParameter("deptName");
//        根据部门名字获取部门id
        try {
            int id = deptService.findIdByName(req.getParameter("deptName"));
            emp.setDeptId(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        根据员工id修改员工信息
        try {
            int i = empService.updateById(emp);
            if (i > 0) {//插入成功
                req.getRequestDispatcher("/empList").forward(req, resp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
